package com.paomi.client.net;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonSyntaxException;
import com.paomi.client.MyApplication;
import com.paomi.client.R;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.bean.UserUtils;
import com.paomi.client.utils.UIUtils;
import com.paomi.client.view.LoadingDialog;
import com.paomi.client.widget.RxToast;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.paomi.client.net.Constants.sServerDate;


/**
 * Created by LS on 2017/6/5 0005.
 * Callback 扩展
 * Note: 适用于RESTFUL风格接口
 * code	注释
 * 0000	操作成功
 * 0001	登录相关错误
 * 0002	header效验相关错误
 * 9999	操作失败
 * 404	页面不存在
 * 500	系统内部错误，请联系程序员
 *
 *
 */

public abstract class BaseCallback<T> implements Callback<T> {

    protected boolean isShowMsg = true;

    public BaseCallback() {}

    /**
     * @param isShowMsg 是否吐司错误消息
     */
    public BaseCallback(boolean isShowMsg) {
        this.isShowMsg = isShowMsg;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        // 同步服务器时间
        sServerDate = response.headers().getDate("date");

        onComplete();
        if(response.isSuccessful()) {
            Response<BaseJSON> baseJSONResponse = (Response<BaseJSON>) response;
            if(baseJSONResponse.body().returnCode!=null){
                if (baseJSONResponse.body().returnCode.equalsIgnoreCase("0000")) {
//                    if(baseJSONResponse.body().getUserInfo()!=null){
//                        UserUtils.getInstance().saveUser1(baseJSONResponse.body().getUserInfo());
//                    }
                    T body = response.body();
                    onResponse(call, body);
                } else {
                    if (baseJSONResponse.body().returnMessage != null) {
                        if (baseJSONResponse.body().returnCode.equals("0001")) {
                            RxToast.info(baseJSONResponse.body().returnMessage);
                           showLoginDialog();
                        } else {
                            RxToast.info(baseJSONResponse.body().returnMessage);
                        }
                    } else {
                        RxToast.info("数据信息无法解析");
                    }
                }
            }else if(baseJSONResponse.body().retCode!=null){
                //判断网络是否连接
                if(getNetworkType()==0){
                    RxToast.info(MyApplication.getAppContext().getResources().getString(R.string.net_null));
                }else{
                    if (baseJSONResponse.body().retMessage != null) {
                        RxToast.info(baseJSONResponse.body().retMessage);
                    }
                }
            }else{
                if(getNetworkType()==0){
                    RxToast.info(MyApplication.getAppContext().getResources().getString(R.string.net_null));
                }else{
                    RxToast.info("数据解析异常");
                }
            }
        } else if(response.code()==404){
            RxToast.info("页面不存在");
        }else if(response.code()==500){
            RxToast.info("系统内部错误，请联系程序员");
        }else if(response.code() < 500) {
            String errorMsg = "请求失败,请检查网络";
            try {
                errorMsg = response.errorBody().string();

            } catch (IOException | JsonSyntaxException e) {
                e.printStackTrace();
            } finally {
                if(getNetworkType()==0){
                    RxToast.info(MyApplication.getAppContext().getResources().getString(R.string.net_null));
                }else{
                    if(isShowMsg && !TextUtils.isEmpty(errorMsg)) RxToast.info(errorMsg);
                    onFailure(response.code());
                }
            }
        }
    }

    public abstract void onResponse(Call<T> call, T result);
    public void onFailure(int code) {
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if(call.isCanceled()) return;
        t.printStackTrace();
        onComplete();
        if(t instanceof ConnectException) {
            RxToast.info("请检查网络");
        }else if(t instanceof SocketException || t instanceof SocketTimeoutException) {
            RxToast.info("请求超时");
        }
        if(getNetworkType()==0){
            RxToast.info(MyApplication.getAppContext().getResources().getString(R.string.net_null));
        }else{
            RxToast.info("数据解析异常");
        }
        onFailure(500);
    }

    public void onComplete() {
        LoadingDialog.get().hideLoading();
    }
    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 1;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 2;
        }
        return netType;
    }
    private static Dialog dialog;
    /**
     * 提示登录弹框
     */
    public static void showLoginDialog(){
        if(dialog==null || !dialog.isShowing()) {
            Activity curActivity = MyApplication.getAppContext().getCurActivity();
            LayoutInflater inflater = LayoutInflater.from(curActivity);
            View view = inflater.inflate(R.layout.dialog_login_out, null);
            dialog = new Dialog(curActivity, R.style.theme_dialog);
            dialog.setContentView(view);
            dialog.show();
            TextView textView = dialog.findViewById(R.id.btn_success);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    if (curActivity == null) return;
                    UIUtils.startLoginActivity(curActivity);
                    UserUtils.getInstance().clearUser();
                }
            });
        }else{
            dialog.dismiss();
        }
    }
}
